package com.bwie.controller;

import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import com.bwie.utils.R;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: ykk
 * @create: 2024-10-08 09:04
 **/
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public R login(@RequestBody User user){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUsername,user.getUsername());
        User user1 = userService.getOne(queryWrapper);
        if(user1==null){
            return R.ERROR(-1,"账号不存在");
        }

        String password = user.getPassword();
        String password1 = user1.getPassword();
        String bcrypt = DigestUtil.bcrypt(password);
        System.out.println("加密后的密码是:"+bcrypt);
        boolean b = BCrypt.checkpw(password, password1);
        if(!b){
            return R.ERROR(-1,"密码不存在");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("id", user1.getId()).compact();
        stringRedisTemplate.opsForValue().set("token:"+user1.getId(),token,15, TimeUnit.MINUTES);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("username",user1.getUsername());
        hashMap.put("password",user1.getPassword());
        hashMap.put("token",token);
        return R.OK(hashMap);
    }
}
